#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = '云絮'
from config import config
import re
import requests

class Proxy:
    def getURIExt(self,uri):
        index=uri.find('.')
        if index!=-1:
            ext=uri[index+1:]
            return ext

    #比较域名是否包含在whitelist里，支持*.baidu.com这类解析
    def hosteq(self,host,whitelist):
        for white in whitelist:
           if host==white:
               return True
           elif white.find('*')!=-1:
               index=white.find('.')
               domain=white[index+1:]
               if host.find(domain)!=-1:
                   return True
        return False

    #1.筛选白名单
    #2.组合请求为sqlmap可以解析的json格式
    #3.过滤静态文件后缀
    def filter(self,req,whitelist):
        reqjson={}
        host=req.host
        scheme=req.scheme
        port=req.port
        path=req.path
        method=req.method
        try:
            query=req.get_query()
        except:
            pass
        print whitelist
        return
        if whitelist:
            if not hosteq(host,self.whitelist):
                return
         #过滤静态资源访问请求
        ext=self.getURIExt(path)
        if ext!=None:
            staticExt=r'(jpg|gif|apk|jpeg|png|js|css|ico|icon|pdf|doc|docx|xls|xlsx|ppt|pptx|rar|zip|7z|swf|exe|iso|rm|rmvb|avi|mid|mp3|mp4|inc)'
            regex = re.compile(staticExt)
            if regex.search(ext):
                return
        try:
            cookies=req.headers['cookie']
            if isinstance(cookies,list):
                cookies=cookies[0]
        except:
            cookies=''
        if port==80:
            url=scheme+'://'+host+path
        else:
            url=scheme+'://'+host+':'+str(port)+path

        if method=='POST':
            data=req.content
            reqjson={"url":url,"data":data,"isscan":0}
            if cookies:
                reqjson["cookie"]=cookies
        elif method=='GET' and query or path.find('*')!=-1:
            reqjson={"url":url,"isscan":0}
            if cookies:
                reqjson["cookie"]=cookies
        if reqjson:
            print reqjson #debug
            a='http://'+config['server']+'/taskadd'
            requests.post(a,reqjson)
